package com.sinosoft.sm.system.security;

import java.io.Serializable;
import java.util.Objects;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import com.sinosoft.sm.system.common.SystemContants;
import com.sinosoft.sm.system.common.exception.ObjectIsNotExistedException;
import com.sinosoft.sm.system.common.utils.EncodeUtil;
import com.sinosoft.sm.user.entity.UserEntity;
import com.sinosoft.sm.user.service.api.UserService;


/**
 * 用户登录授权service
 * @author xiaoxiong
 */
public class UserRealmService extends AuthorizingRealm {

	public static final String HASH_ALGORITHM = "SHA-1";	//	hash算法名称
	private static final int HASH_INTERATIONS = 1024;	//	循环遍历次数
	
	private UserService userService;
	
	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	/**
	 * 重写init，增加密码的校验算法
	 */
	@Override
	protected void onInit() {
		super.onInit();
		
		this.initCredentialsMatcher();	//	设定Password校验的Hash算法与迭代次数
	}
	
	/**
	 * 认证回调函数,登录时调用.
	 */
	@SuppressWarnings("unused")
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken; 
		UserEntity user = null;
		try {
			user = userService.getUserByUsername(token.getUsername());
		} catch (ObjectIsNotExistedException e) {
			throw new UnknownAccountException();
		}
		if(SystemContants.USER_STATE_ON.equals(user.getState())){
			if (user != null) {
				byte[] salt = EncodeUtil.decodeHex(user.getSalt());
				ShiroUser shiroUser = new ShiroUser(user.getUsername());
				Session session = SecurityUtils.getSubject().getSession();	
				session.setAttribute("user", user);
				return new SimpleAuthenticationInfo(shiroUser, user.getPassword(), ByteSource.Util.bytes(salt), getName());
			} else {
				throw new UnknownAccountException();
			}
		}else{
			throw new UnknownAccountException();
		}
	}

	/**
	 * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		ShiroUser shiroUser = (ShiroUser) principals.getPrimaryPrincipal();
		UserEntity user = null;
		try {
			user = userService.getUserByUsername(shiroUser.username);
		} catch (ObjectIsNotExistedException e) {
			e.printStackTrace();
		}
		
		//把principals放session中 key=username value=principals
		SecurityUtils.getSubject().getSession().setAttribute(
				String.valueOf(user.getUsername()),SecurityUtils.getSubject().getPrincipals());
		
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		return info;
	}

	/**
	 * 设定Password校验的Hash算法与迭代次数.
	 */
	@SuppressWarnings({ "static-access" })
	private void initCredentialsMatcher() {
		HashedCredentialsMatcher matcher = new HashedCredentialsMatcher(this.HASH_ALGORITHM);
		matcher.setHashIterations(this.HASH_INTERATIONS);
		setCredentialsMatcher(matcher);
	}
	
	/**
	 * 自定义Authentication对象，使得Subject除了携带用户的登录名外还可以携带更多信息.
	 */
	public static class ShiroUser implements Serializable {
		private static final long serialVersionUID = -1373760761780840081L;
		private String username;
		private String nickname;
		private String isadmin;	//	是否是应用管理员

		public ShiroUser(String username) {
			this.username = username;
		}

		public String getNickname() {
			return this.nickname;
		}

		public String getIsadmin() {
			return this.isadmin;
		}
		
		public void setIsadmin(String isadmin) {
			this.isadmin = isadmin;
		}
		
		/**
		 * 本函数输出将作为默认的<shiro:principal/>输出
		 */
		@Override
		public String toString() {
			return username;
		}

		/**
		 * 重载hashCode,只计算username
		 */
		@Override
		public int hashCode() {
			return Objects.hashCode(username);
		}

		/**
		 * 重载equals,只计算username
		 */
		@Override
		public boolean equals(Object obj) {
			if (this == obj) {
				return true;
			}
			if (obj == null) {
				return false;
			}
			if (getClass() != obj.getClass()) {
				return false;
			}
			ShiroUser other = (ShiroUser) obj;
			if (username == null) {
				if (other.username != null) {
					return false;
				}
			} else if (!username.equals(other.username)) {
				return false;
			}
			return true;
		}
	}
	
	@Override
    public void clearCachedAuthorizationInfo(PrincipalCollection principals) {
        super.clearCachedAuthorizationInfo(principals);
    }

    @Override
    public void clearCachedAuthenticationInfo(PrincipalCollection principals) {
        super.clearCachedAuthenticationInfo(principals);
    }

    @Override
    public void clearCache(PrincipalCollection principals) {
        super.clearCache(principals);
    }

    public void clearAllCachedAuthorizationInfo() {
        getAuthorizationCache().clear();
    }

    public void clearAllCachedAuthenticationInfo() {
        getAuthenticationCache().clear();
    }

    public void clearAllCache() {
        clearAllCachedAuthenticationInfo();
        clearAllCachedAuthorizationInfo();
    }
 
}
